package main

import (
	"fmt"
	"go-study/algorithm/common"
)

// 如何把链表以 k 个节点为一组进行翻转

func main() {
	head := &common.LNode{}
	common.CreateNode1(head, 8)
	fmt.Println("顺序输出：", head)
	reverseK(head, 3)
	fmt.Println("逆序输出：", head)
}

func reverse(head *common.LNode) *common.LNode {
	if head == nil || head.Next == nil {
		return head
	}

	var previous, next *common.LNode
	current := head

	for current != nil {
		next = current.Next
		current.Next = previous
		previous = current
		current = next
	}

	return previous
}

func reverseK(head *common.LNode, k int) {
	if head == nil || head.Next == nil {
		return
	}

	previous := head
	begin := head.Next
	var end, next *common.LNode

	for begin != nil {
		end = begin
		for i := 1; i < k; i++ {
			if end.Next != nil {
				end = end.Next
			} else {
				return
			}
		}

		next = end.Next

		end.Next = nil
		previous.Next = reverse(begin)
		begin.Next = next

		previous = begin
		begin = next
	}
}
